package com.zeng.jiudian.filter;

import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author JJ_yo
 * @Date 2020/7/29 - 9:48
 */
@WebFilter("/*")
public class MyFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
        System.out.println("过滤器初始化------");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        /* 允许跨域的主机地址 */
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        resp.setHeader("Access-Control-Allow-Methods", "*");
        /* 重新预检验跨域的缓存时间 (s) */
        resp.setHeader("Access-Control-Max-Age", "3600");
        /* 允许跨域的请求头 */
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
        /* 是否携带cookie */
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("XDomainRequestAllowed", "1");

        String path = req.getServletPath();
        if (path.startsWith("/back/"))
        {
            //Object username = req.getSession().getAttribute("username");
            Jedis jedis = new Jedis();
            jedis.select(1);
            String username = jedis.get(req.getParameter("loginUsername"));

            if (username != null && !"".equals(username))
            {
                filterChain.doFilter(req, resp);
            }
            else
            {
                resp.sendRedirect("/login.html");
            }
        }
        else
        {
            filterChain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy()
    {
        System.out.println("过滤器销毁------");
    }
}
